import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from tools.DBUtil import DBUtil

class EmailSender:
    def __init__(self):
        res = DBUtil.select_one("select * from system_config")
        print(res["email"], res["passwd"], res["server"], res["port"])
        if res:
            self.sender_email = res['email']
            self.sender_password = res['passwd']
            self.smtp_server = res['server']
            self.smtp_port = res['port']
            self.server = None
        else:
            print("未找到发送邮件配置")

    def get_server(self):
        if self.server is None:
            self.server = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port)
            self.server.login(self.sender_email, self.sender_password)
            print("连接服务器成功")

    def close_server(self):
        if self.server:
            print("关闭服务器连接")
            self.server.quit()

    def send_email(self, receiver_email, subject, body):
        # 创建消息对象
        message = MIMEMultipart("alternative")
        message["From"] = f"虚拟主机自助申请系统<{self.sender_email}>"
        message["To"] = receiver_email
        message["Subject"] = subject

        # 添加邮件正文
        message.attach(MIMEText(body, "html"))

        try:
            self.get_server()
            text = message.as_string()
            self.server.sendmail(self.sender_email, receiver_email, text)

        except Exception as e:
            print(f"邮件发送失败: {e}")
            return False
        else:
            print("邮件发送成功")
            self.close_server()
            return True

# 示例使用
if __name__ == "__main__":
    sender_email = "1064250954@qq.com"
    sender_password = "panmkkyckihxbccf"
    sender_server = "smtp.qq.com"
    sender_port = 465
    receiver_email = "1208724781@qq.com"
    subject = "测试邮件"
    body = "这是一封测试邮件。"

    email_sender = EmailSender().send_email(receiver_email, subject, body)
